<template>
  <!-- 新建编辑弹框 -->
  <base-modal :show.sync="visible" :title="dialogTitle" width="600px" class="project-type-work-log-dialog" @closed="closeDialog">
    <form-builder v-if="fields.length" ref="workLogFormRef" v-loading="formLoading" :fields="fields" :value="form" mode="projectTypeWorkLogDialog" @update="update" 
      :formEditingMode="formEditingMode"
      @getDeleteFiles="getDeleteFiles"></form-builder>
    <div slot="footer" class="dialog-footer">
      <el-button @click="closeDialog">{{ $t('common.base.cancel') }}</el-button>
      <el-button type="primary" :loading="showLoading" @click="submit">{{ $t('common.base.submit') }}</el-button>
    </div>
  </base-modal>
</template>
<script>
import { reactive, toRefs, ref, computed } from 'vue';
import i18n from '@src/locales';

export default {
  props: {
    fields: {
      type: Array,
      default: () => [],
    },
    form: {
      type: Object,
      default: () => ({}),
    },
    dialogTitleType: {
      type: String,
      default: '',
    },
  },
  emits: ['submitWorkLog', 'updateWorkLog'],
  setup(props, { emit }) {
    const workLogFormRef = ref();

    const state = reactive({
      visible: false,
      showLoading: false,
      formLoading: false,
      needServerDeleFiles: []
    });

    const dialogTitle = computed(() => {
      const obj = {
        new: i18n.t('common.projectManage.detail.workLog.title1'),
        edit: i18n.t('common.projectManage.detail.workLog.title2'),
      };
      return obj[props.dialogTitleType];
    });

    const formEditingMode = computed(() => {
      return props.dialogTitleType === 'edit' ? 'edit' : 'create'
    })

    const openDialog = () => {
      state.visible = true;
    };

    const closeDialog = () => {
      state.visible = false;
    };

    const update = val => {
      emit('updateWorkLog', val);
    };

    const submit = () => {
      try {
        workLogFormRef.value.validate(false).then(valid => {
          if (!valid) return false;

          state.showLoading = true;
          emit('submitWorkLog');
        });
      } catch (err) {}
    };

    // 删除附件
    const getDeleteFiles = (files) => {
      state.needServerDeleFiles = [...state.needServerDeleFiles, ...files]
    }
    return {
      workLogFormRef,
      dialogTitle,
      ...toRefs(state),
      update,
      submit,
      openDialog,
      closeDialog,
      formEditingMode,
      getDeleteFiles
    };
  },
};
</script>
<style lang="scss" scoped>
</style>